package pers.mtx.myapplication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zlylib.fileselectorlib.FileSelector;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import pers.mtx.myapplication.db.MyDatabaseHelper;
import pers.mtx.myapplication.model.Data;
import pers.mtx.myapplication.model.ResUserData;
import pers.mtx.myapplication.service.WebSocketService;

public class LogActivity extends AppCompatActivity {
//    private WebSocketService webSocketService;
    public static String TAG = "LogActivity";
    @BindView(R.id.test) TextView test;
    @BindView(R.id.UserList) LinearLayout userList;
    private MyDatabaseHelper dbHelper;
    private SQLiteDatabase db;
    private final OkHttpClient client = new OkHttpClient();
    ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        requestPermission();
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.log_activity);
        ButterKnife.bind(this);

        dbHelper = new MyDatabaseHelper(LogActivity.this, 5);
        db = dbHelper.getWritableDatabase();
        db.execSQL("DROP TABLE user;");
        db.execSQL("create table user(userName varchar(64) PRIMARY KEY,nickName varchar(64));");
        db.execSQL("DROP TABLE chat_record;");
        db.execSQL("create table chat_record\n" +
                "(" +
                "    send_time datetime    ," +
                "    sender_id    mediumtext  ," +
                "    receiver_id  mediumtext  ," +
                "    message      mediumtext  ," +
                "    msg_type     int         ," +
                "    rb           mediumtext  ," +
                "    msg_id       varchar(64) " +
                "        primary key\n" +
                ")" +
                ";");
//        Intent intent = new Intent(LogActivity.this, WebSocketService.class);
//        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);

//        FileSelector.from(this)
//                // .onlyShowFolder()  //只显示文件夹
//                //.onlySelectFolder()  //只能选择文件夹
//                // .isSingle() // 只能选择一个
//                .setMaxCount(5) //设置最大选择数
//                .setFileTypes("png", "doc","apk", "mp3", "gif", "txt", "mp4", "zip") //设置文件类型
//                .setSortType(FileSelector.BY_NAME_ASC) //设置名字排序
//                //.setSortType(FileSelector.BY_TIME_ASC) //设置时间排序
//                //.setSortType(FileSelector.BY_SIZE_DESC) //设置大小排序
//                //.setSortType(FileSelector.BY_EXTENSION_DESC) //设置类型排序
//                .requestCode(1) //设置返回码
//                .setTargetPath("/storage/emulated/0/Android/data/") //设置默认目录
//                .start();

    }


//    private ServiceConnection mServiceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder iBinder) {
//            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) iBinder;
//            webSocketService = binder.getService();
//            Log.d("ChatActivity", "onServiceConnected");
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            Log.d("ChatActivity", "onServiceDisconnected");
//        }
//    };
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23){
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
    }
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 1:
                    Data data = (Data)msg.obj;
                    TextView textView = new TextView(LogActivity.this);
                    textView.setTextSize(15);
                    textView.setTextColor(Color.BLACK);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100);
                    layoutParams.setMargins(50,0,0,0);
                    textView.setLayoutParams(layoutParams);
                    textView.setOnClickListener(v -> {
                        TextView v1 = (TextView) v;
                        Data tag = (Data) v1.getTag();
                        Log.d(TAG, "handleMessage: "+tag.getUsername());
                        Intent intent = new Intent(LogActivity.this,ChatListActivity.class);
                        intent.putExtra("id",tag.getUsername());
                        startActivity(intent);
                    });
                    textView.setText(data.getNickname());
                    textView.setTag(data);
                    userList.addView(textView);
                    break;
            }
        }
    };


    public void run() throws Exception {
        Request request = new Request.Builder()
                .url("http://192.168.1.109:8080/app/user/api/list?sex=0&classesId=110")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                    ResUserData data = mapper.readValue(responseBody.string(), ResUserData.class);
                    for (int i = 0; i < data.getData().size(); i++) {
                        ContentValues values = new ContentValues();
                        Data data1 = data.getData().get(i);
                        values.put("nickName",data1.getNickname());
                        values.put("userName",data1.getUsername());
                        db.insertOrThrow("user",null,values);
                        Log.d(TAG, "onResponse: "+values);
                        Message message = new Message();
                        message.what=1;
                        message.obj = data1;
                        handler.sendMessage(message);

                    }
                }
            }
        });
    }


    @OnClick(R.id.test) void test(){

        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
